<template>
  <div class="login-container">
    <el-card class="box-card">
      <!-- 标题 -->
      <div class="title"></div>
      <!-- 使用element-ui的表单 -->
      <el-form ref="form" :model="user" :rules="rules">
        <!-- 一个 el-form-item 就是一行 -->
        <el-form-item prop="username">
          <el-input
            v-model="user.username"
            prefix-icon="el-icon-user"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="user.password"
            show-password
            type="password"
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
      <el-link :underline="false" @click="$router.push('/reg')">还没有账号，去注册</el-link>
    </el-card>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'MyLogin',
  data() {
    return {
      user: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/,
            message: '字母开头，允许5-16字节，允许字母数字下划线',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入正确的密码格式', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z]\w{5,17}$/,
            message: '以字母开头，长度在6~18之间，只能包含字母、数字和下划线)',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    login() {
      // 当点击登录的时候，先进行完整的验证，验证不通过就return，验证通过则提交数据
      // 表单.validator(valid => { valid===true |  valid===false })
      this.$refs.form.validate(async valid => {
        if (!valid) return // 验证不通过，return
        const { data: res } = await loginAPI(this.user)
        if (res.code === 0) {
          // 登录成功：提示、重置表单、跳转到主页
          this.$message.success(res.message)
          this.$refs.form.resetFields() // 重置表单
          this.$store.commit('user/updateToken', res.token) // 调用mutations中的方法将服务端返回的token存储到本地
          this.$router.push('/') // 跳转到主页
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style>
.login-container {
  background-image: url('@/assets/images/login_bg.jpg');
  background-size: cover;
  height: 100%;
}
.el-card {
  width: 400px;
  height: 400px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.el-form-item {
  margin-top: 35px;
}
.title {
  height: 40px;
  background: url('@/assets/images/login_title.png') top center no-repeat;
  /* background-size: cover; */
}
.el-button {
  margin-top: 10px;
  width: 100%;
}
</style>
